import {
  Breadcrumb,
  Card,
  Form,
  Button,
  Radio,
  Select,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd';

import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Link, useHistory } from 'react-router-dom';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import styles from './Article.module.scss';
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  deleteArticle,
  getArticles,
  getChannels,
} from '@/store/actions/article';
import img404 from '@/assets/error.png';

export const Article = () => {
  // hooks
  const dispatch = useDispatch();
  const history = useHistory();

  // 文章列表查询条件
  const [filter, setFilter] = useState({
    status: -1, // 文章状态
    channelId: -1, // 频道
    dateStart: '', // 开始日期
    dateEnd: '', // 截止日期
    page: 1, // 页码
    pageSize: 10, // 每页条数
  });

  // 从redux中读取频道数据
  const channels = useSelector((state) => state.article.channels);
  // 文章列表
  const list = useSelector((state) => state.article.list);
  // 文章总数
  const total = useSelector((state) => state.article.total);

  // 获取文章列表数据
  useEffect(() => {
    dispatch(getArticles(filter));
  }, [filter, dispatch]);

  // 获取频道数据
  useEffect(() => {
    dispatch(getChannels());
  }, [dispatch]);

  // 事件处理函数
  const onFinish = (values) => {
    console.log(values);
    let newFilter = {};
    newFilter.status = values.status;
    newFilter.channelId = values.channelId;
    if (values.date) {
      newFilter.dateStart = values.date[0].format('YYYY-MM-DD HH:mm:ss');
      newFilter.dateEnd = values.date[1].format('YYYY-MM-DD HH:mm:ss');
    }
    // 设置页面的新的查询状态，页面刷新，根据新的条件查询文章列表
    setFilter({
      ...filter,
      ...newFilter,
    });
  };

  // 删除文章
  const delArticle = (id) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <div>xxx</div>,
      content: '此操作将永久删除该文章, 是否继续?',
      onOk: () => {
        console.log('删除文章', id);
        dispatch(deleteArticle(id));
        // 重新获取文章列表
        dispatch(getArticles(filter));
      },
    });
  };

  // 分页被点击事件处理函数
  const changePage = (page, pageSize) => {
    console.log(page, pageSize);
    setFilter({
      ...filter,
      page,
      pageSize,
    });
  };

  // table 的表头
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover || img404} width={200} height={150} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        if (data === 0) {
          return <Tag color="green">草稿</Tag>;
        } else if (data === 1) {
          return <Tag color="green">待审核</Tag>;
        } else if (data === 2) {
          return <Tag color="green">审核通过</Tag>;
        } else if (data === 3) {
          return <Tag color="green">审核失败</Tag>;
        }
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      // 如果 key 无法在在data中查找到值，则 render 函数的第一个参数就是当前行的值
      render: (record) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${record.id}`)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              onClick={() => delArticle(record.id)}
              icon={<DeleteOutlined />}
            />
          </Space>
        );
      },
    },
  ];

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator={'>'}>
            <Breadcrumb.Item>
              <Link to={'/home'}>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 筛选 */}
        <Form initialValues={{ status: -1 }} onFinish={onFinish}>
          <Form.Item label={'状态'} name={'status'}>
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label={'频道'} name={'channelId'}>
            <Select placeholder={'请选择频道'} style={{ width: 264 }}>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label={'日期'} name={'date'}>
            <DatePicker.RangePicker locale={locale} />
          </Form.Item>
          <Form.Item>
            <Button type={'primary'} htmlType={'submit'}>
              筛 选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`筛选出${total}条`} style={{ marginTop: 24 }}>
        <Table
          rowKey={'id'}
          columns={columns}
          dataSource={list}
          pagination={{
            page: filter.page,
            pageSize: filter.pageSize,
            total: total,
            onChange: changePage,
          }}
        ></Table>
      </Card>
    </div>
  );
};
